<template>
  <el-dialog :title="form.classId ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="form.className" placeholder="请输入班级名称" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="班主任" prop="headTeacher">
            <el-input v-model="form.headTeacher" placeholder="请输入班主任" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="课程分类" prop="courseCategory">
            <el-select v-model="form.courseCategory" placeholder="请选择课程分类">
              <el-option :value="item.value" :label="item.label" v-for="(item, index) in course_category"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="期次" prop="period">
            <el-input v-model="form.period" placeholder="请输入期次" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20" v-if="form.classId">
          <el-form-item label="添加学生">
            <el-row :gutter="24">
              <el-col :span="24" class="mb20">
                <div class="mb20">
                  <el-button type="primary" @click="showMode">+</el-button>
                </div>
              </el-col>
              <el-col :span="24" class="mb20">
                <div class="mb20 tags" v-if="selectUserList.length > 0">
                  <el-tag v-for="tag in selectUserList" :key="tag" closable :disable-transitions="false"
                    @close="handleCloseTag(tag)">
                    {{ tag.name }}
                  </el-tag>
                </div>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
    <selectUser ref="selectUserRef" :ismultiple="ismultiple" :classId="form.classId" @selectUserFun="selectUserFun">
    </selectUser>

  </el-dialog>
</template>

<script setup lang="ts" name="ClassesDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj, validateExist } from '/@/api/admin/classes'
import { addStudent, fetchListClass, deluser } from '/@/api/admin/classStudent'
import { rule } from '/@/utils/validate';
import selectUser from '../../../components/selectUser/index.vue';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const selectUserRef = ref()
const selectUserList = ref([])
const ismultiple = ref(true)

// 定义字典
const { course_category } = useDict('course_category')

// 提交表单数据
const form = reactive({
  classId: '',
  className: '',
  headTeacher: '',
  courseCategory: '',
  period: '',
});

// 定义校验规则
const dataRules = ref({
  className: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
  headTeacher: [{ required: true, message: '班主任不能为空', trigger: 'blur' }],
  courseCategory: [{ required: true, message: '课程分类不能为空', trigger: 'blur' }],
  period: [{ required: true, message: '期次不能为空', trigger: 'blur' }],
})

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.classId = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取classes信息
  if (id) {
    form.classId = id
    getClassesData(id)
    getClassStudentList(id)
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;

  try {
    loading.value = true;
    // form.classId ? await putObj(form) : await addObj(form);
    if (form.classId) {
      await putObj(form)
    } else {
      let data = {
        className: form.className,
        courseCategory: form.courseCategory,
        headTeacher: form.headTeacher,
        period: form.period,
      }
      console.log('data', data);
      await addObj(data);
    }
    useMessage().success(form.classId ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
  if (selectUserList.value.length > 0) {
    let data = {
      classId: form.classId,
      studentIds: selectUserList.value.map(item => item.id)
    }
    addStudent(data).then((res: any) => {

    })
  }
};


// 初始化表单数据
const getClassesData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj({ classId: id, inClass: 1 }).then((res: any) => {
    Object.assign(form, res.data[0])
    form.courseCategory = formatstatus(form.courseCategory)
  }).finally(() => {
    loading.value = false
  })
};
const formatstatus = (num) => {
  if (num || num == 0) {
    let num2 = num + ''
    return num2
  } else {
    return ''
  }
}
const getClassStudentList = (id: string) => {
  // 获取数据
  loading.value = true
  fetchListClass({ classId: id, inClass: 1 }).then((res: any) => {
    selectUserList.value = res.data || []
  }).finally(() => {
    loading.value = false
  })
};
const handleClose = (done) => {
  dialogVisible.value = false
}
const showMode = () => {
  console.log('showMode', selectUserRef.value);
  selectUserRef.value.showMode()
}
const selectUserFun = (data) => {
  selectUserList.value = selectUserList.value.concat(data);
  console.log('selectUserFun', data);
}
//删除标签
const handleCloseTag = (tag) => {
  deluser({ classId: form.classId, studentId: tag.id }).then((res: any) => {
    console.log(res);
    selectUserList.value = selectUserList.value.filter(item => item.id !== tag.id)
  })

}
// 暴露变量
defineExpose({
  openDialog
});
</script>
<style scoped lang="scss">
.tags {
  .el-tag {
    margin-right: 3px;
  }
}
</style>
